<!--销售工作台-->
<template>
  <div class="sales-workbench">
    <!-- 数据概览区域 -->
    <div class="data-overview">
      <div class="overview-title">数据概览 <span class="date">{{ currentDate }}</span></div>
      
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card sales" v-loading="loading.statistics">
          <div class="stat-icon">💰</div>
          <div class="stat-content">
            <div class="stat-label">本月销售额</div>
            <div class="stat-value">{{ formatAmount(statistics.monthlySales) }}</div>
          </div>
        </div>
        <div class="stat-card orders" v-loading="loading.statistics">
          <div class="stat-icon">📋</div>
          <div class="stat-content">
            <div class="stat-label">本月订单数</div>
            <div class="stat-value">{{ statistics.monthlyOrders }}</div>
          </div>
        </div>
        <div class="stat-card customers" v-loading="loading.statistics">
          <div class="stat-icon">👥</div>
          <div class="stat-content">
            <div class="stat-label">本月新客户</div>
            <div class="stat-value">{{ statistics.newCustomers }}</div>
          </div>
        </div>
        <div class="stat-card delivery" v-loading="loading.statistics">
          <div class="stat-icon">🚚</div>
          <div class="stat-content">
            <div class="stat-label">本月发货金额</div>
            <div class="stat-value">{{ formatAmount(statistics.shippingAmount) }}</div>
          </div>
        </div>
        <div class="stat-card target" v-loading="loading.statistics">
          <div class="stat-icon">🎯</div>
          <div class="stat-content">
            <div class="stat-label">目标完成率</div>
            <div class="stat-value">{{ statistics.targetCompletion }}%</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：销售分析 -->
      <div class="left-panel">
        <div class="panel-header">
          <h3>11个月销售分布</h3>
        </div>
        <div class="chart-section">
          <!-- 圆饼图 -->
          <div class="pie-chart">
            <div class="pie-chart-container">
              <div class="pie-center">
                <div class="pie-value">{{ formatAmount(statistics.monthlySales) }}</div>
                <div class="pie-label">销售总额</div>
              </div>
            </div>
          </div>
          <!-- 客户分析表格 -->
          <div class="customer-analysis" v-loading="loading.distribution">
            <div class="analysis-item" v-for="item in orderDistribution" :key="item.category || item.type">
              <span class="customer-type">{{ item.category || item.type || '未分类' }}</span>
              <span class="customer-amount">{{ formatAmount(item.amount || item.value || 0) }}</span>
              <span class="customer-percent">{{ ((item.percentage || item.ratio || 0) * 100).toFixed(1) }}%</span>
            </div>
            <div class="analysis-item" v-if="!orderDistribution || orderDistribution.length === 0">
              <span class="customer-type" style="color: #999; text-align: center; width: 100%;">暂无数据</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：销售目标进度和常用功能 -->
      <div class="right-panel">
        <!-- 常用功能 -->
        <div class="functions-panel">
          <div class="panel-header">
            <h3>常用功能</h3>
          </div>
          <div class="function-grid">
            <div class="function-item" @click="navigateToModule('销售订单')">
              <div class="function-icon" style="background: #f56c6c;">📋</div>
              <div class="function-name">订单管理</div>
            </div>
            <div class="function-item" @click="navigateToModule('客户管理')">
              <div class="function-icon" style="background: #909399;">👥</div>
              <div class="function-name">客户管理</div>
            </div>
            <div class="function-item" @click="navigateToModule('库存明细')">
              <div class="function-icon" style="background: #e6a23c;">📦</div>
              <div class="function-name">库存管理</div>
            </div>
            <div class="function-item" @click="navigateToModule('发货单')">
              <div class="function-icon" style="background: #67c23a;">🚚</div>
              <div class="function-name">发货管理</div>
            </div>
          </div>
        </div>
        
        <!-- 销售目标进度 -->
        <div class="progress-panel">
          <div class="panel-header">
            <h3>销售目标进度</h3>
          </div>
          <div class="progress-section">
            <div class="progress-item">
              <div class="progress-label">本月销售目标</div>
              <div class="progress-bar">
                <div class="progress-fill" :style="`width: ${statistics.targetCompletion}%`"></div>
              </div>
              <div class="progress-value">{{ statistics.targetCompletion }}%</div>
            </div>
            <div class="progress-item">
              <div class="progress-label">客户拓展目标</div>
              <div class="progress-bar">
                <div class="progress-fill" :style="`width: ${Math.min(statistics.newCustomers * 10, 100)}%`"></div>
              </div>
              <div class="progress-value">{{ Math.min(statistics.newCustomers * 10, 100) }}%</div>
            </div>
            <div class="progress-item">
              <div class="progress-label">订单完成率</div>
              <div class="progress-bar">
                <div class="progress-fill" :style="`width: ${Math.min((statistics.monthlyOrders / 100) * 100, 100)}%`"></div>
              </div>
              <div class="progress-value">{{ Math.min((statistics.monthlyOrders / 100) * 100, 100) }}%</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部订单列表 -->
    <div class="orders-section">
      <div class="section-header">
        <h3>关键词</h3>
        <div class="search-controls">
          <input type="text" placeholder="请输入关键词" class="search-input">
          <select class="filter-select">
            <option>订单状态</option>
            <option>全部</option>
          </select>
          <input type="date" class="date-input" placeholder="期望发货时间">
          <button class="search-btn">搜索</button>
          <button class="reset-btn">重置</button>
        </div>
      </div>
      
      <div class="orders-table" v-loading="loading.orders">
        <table>
          <thead>
            <tr>
              <th>序号</th>
              <th>销售订单号</th>
              <th>订单商品数量</th>
              <th>已发货数量</th>
              <th>订单总额</th>
              <th>成交总额</th>
              <th>已发货总额</th>
              <th>待发货总额</th>
              <th>已退货总额</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(order, index) in ordersList" :key="order.id">
              <td>{{ index + 1 }}</td>
              <td><a href="#" class="order-link">{{ order.orderNumber }}</a></td>
              <td>{{ order.totalQuantity }}</td>
              <td>{{ order.shippedQuantity }}</td>
              <td>¥{{ formatAmount(order.totalAmount) }}</td>
              <td>¥{{ formatAmount(order.dealAmount) }}</td>
              <td>¥{{ formatAmount(order.shippedAmount) }}</td>
              <td>¥{{ formatAmount(order.pendingAmount) }}</td>
              <td>¥{{ formatAmount(order.returnAmount) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div class="table-pagination">
        <div class="pagination-info">
          <span>共 {{ pagination.total }} 条记录，每页 {{ pagination.pageSize }} 条</span>
        </div>
        <div class="pagination-controls">
          <button 
            class="page-btn" 
            :class="{ disabled: pagination.currentPage === 1 }"
            @click="changePage(pagination.currentPage - 1)"
            :disabled="pagination.currentPage === 1">
            上一页
          </button>
          
          <button 
            v-for="page in getVisiblePages()" 
            :key="page"
            class="page-btn" 
            :class="{ active: page === pagination.currentPage }"
            @click="changePage(page)">
            {{ page }}
          </button>
          
          <span v-if="pagination.totalPages > 7 && pagination.currentPage < pagination.totalPages - 3">...</span>
          
          <button 
            class="page-btn" 
            :class="{ disabled: pagination.currentPage === pagination.totalPages }"
            @click="changePage(pagination.currentPage + 1)"
            :disabled="pagination.currentPage === pagination.totalPages">
            下一页
          </button>
          
          <select v-model.number="pagination.pageSize" @change="onPageSizeChange" class="page-size-select">
            <option value="5">5条/页</option>
            <option value="10">10条/页</option>
            <option value="20">20条/页</option>
            <option value="50">50条/页</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { dashboardApi } from '@/api/dashboard.js'

export default {
  name: 'SalesWorkbench',
  data() {
    return {
      // 搜索和筛选
      searchKeyword: '',
      statusFilter: '',
      
      // 统计数据
      statistics: {
        monthlySales: 0,
        monthlyOrders: 0,
        newCustomers: 0,
        shippingAmount: 0,
        targetCompletion: 0
      },
      
      // 销售趋势数据
      salesTrend: [],
      
      // 订单分布数据
      orderDistribution: [],
      
      // 最新订单列表
      latestOrders: [],
      
      // 库存预警
      inventoryAlerts: [],
      
      // 加载状态
      loading: {
        statistics: false,
        orders: false,
        distribution: false
      },
      
      // 底部订单列表数据
      ordersList: [],
      
      // 分页相关数据
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        totalPages: 1
      },
      
      // 原有订单数据（保留用于其他功能）
      orders: [],
      
      // 重要客户数据
      topCustomers: [],

      // 销售趋势数据
      salesTrend: []
    }
  },
  async mounted() {
    await this.loadDashboardData()
  },
  computed: {
    currentDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      return `${year}年${month}月`
    },
    filteredOrders() {
      let filtered = this.orders
      if (this.searchKeyword) {
        filtered = filtered.filter(order => 
          order.orderNumber.includes(this.searchKeyword) ||
          order.customerName.includes(this.searchKeyword)
        )
      }
      if (this.statusFilter) {
        filtered = filtered.filter(order => order.status.text === this.statusFilter)
      }
      return filtered
    }
  },
  methods: {
    /**
     * 加载仪表板数据
     */
    async loadDashboardData() {
      try {
        // 并行加载所有数据
        await Promise.all([
          this.loadStatistics(),
          this.loadLatestOrders(),
          this.loadOrderDistribution(),
          this.loadSalesTrend()
        ])
      } catch (error) {
        console.error('加载仪表板数据失败:', error)
        this.$message.error('加载数据失败，请稍后重试')
      }
    },

    /**
     * 加载统计数据
     */
    async loadStatistics() {
      this.loading.statistics = true
      try {
        const response = await dashboardApi.getStatistics()
        if (response.data && response.data.success) {
          const data = response.data.data
          this.statistics = {
            monthlySales: data.totalRevenue || 0,
            monthlyOrders: data.totalOrders || 0,
            newCustomers: data.totalCustomers || 0,
            shippingAmount: data.totalRevenue || 0,
            targetCompletion: Math.round((data.totalRevenue / 10000000) * 100) || 0
          }
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      } finally {
        this.loading.statistics = false
      }
    },

    /**
     * 加载最新订单
     */
    async loadLatestOrders() {
      this.loading.orders = true
      try {
        const response = await dashboardApi.getLatestOrders(this.pagination.currentPage, this.pagination.pageSize)
        if (response.data && response.data.code === 200) {
          const data = response.data.data
          this.latestOrders = data.data || []
          
          // 更新分页信息
          this.pagination.total = data.total || 0
          this.pagination.totalPages = data.totalPages || 1
          this.pagination.currentPage = data.page || 1
          
          // 更新订单列表数据格式
          this.ordersList = this.latestOrders.map((order, index) => ({
            id: order.orderId || index + 1,
            orderNumber: order.orderNumber || `SO${Date.now()}${index}`,
            totalQuantity: order.productCount || 0,
            shippedQuantity: order.shippedQuantity || 0,
            totalAmount: order.orderAmount || 0,
            dealAmount: order.orderAmount || 0,
            shippedAmount: order.amountReceived || 0,
            pendingAmount: order.amountCollected || 0,
            returnAmount: order.refundedTotal || 0
          }))
        }
      } catch (error) {
        console.error('加载最新订单失败:', error)
      } finally {
        this.loading.orders = false
      }
    },

    /**
     * 加载订单分布数据
     */
    async loadOrderDistribution() {
      this.loading.distribution = true
      try {
        const response = await dashboardApi.getOrderDistribution()
        if (response.data && response.data.success) {
          this.orderDistribution = response.data.data || []
        }
      } catch (error) {
        console.error('加载订单分布数据失败:', error)
      } finally {
        this.loading.distribution = false
      }
    },

    /**
     * 加载销售趋势数据
     */
    async loadSalesTrend() {
      try {
        const response = await dashboardApi.getSalesTrend(11)
        if (response.data && response.data.success) {
          this.salesTrend = response.data.data || []
        }
      } catch (error) {
        console.error('加载销售趋势数据失败:', error)
      }
    },

    /**
     * 格式化金额显示
     */
    formatAmount(amount) {
      if (amount >= 10000) {
        return (amount / 10000).toFixed(1) + '万'
      }
      return amount.toLocaleString()
    },

    /**
     * 刷新数据
     */
    async refreshData() {
      await this.loadDashboardData()
      this.$message.success('数据刷新成功')
    },

    searchOrders() {
      // 搜索订单逻辑
      console.log('搜索订单:', this.searchKeyword, this.statusFilter)
    },
    formatCurrency(amount) {
      return amount.toLocaleString()
    },

    /**
     * 分页相关方法
     */
    changePage(page) {
      if (page < 1 || page > this.pagination.totalPages || page === this.pagination.currentPage) {
        return
      }
      this.pagination.currentPage = page
      this.loadLatestOrders()
    },

    getVisiblePages() {
      const current = this.pagination.currentPage
      const total = this.pagination.totalPages
      const pages = []
      
      if (total <= 7) {
        // 如果总页数小于等于7，显示所有页码
        for (let i = 1; i <= total; i++) {
          pages.push(i)
        }
      } else {
        // 如果总页数大于7，智能显示页码
        if (current <= 4) {
          // 当前页在前4页
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
          pages.push(total)
        } else if (current >= total - 3) {
          // 当前页在后4页
          pages.push(1)
          for (let i = total - 4; i <= total; i++) {
            pages.push(i)
          }
        } else {
          // 当前页在中间
          pages.push(1)
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i)
          }
          pages.push(total)
        }
      }
      
      return pages
    },

    onPageSizeChange() {
      this.pagination.currentPage = 1
      this.loadLatestOrders()
    },

    /**
     * 导航到指定模块
     */
    navigateToModule(moduleName) {
      // 通过事件通知父组件切换页面
      this.$emit('navigate', moduleName)
    }

  }
}
</script>

<style scoped>
.sales-workbench {
  padding: 20px 20px 10px 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 20px);
  font-family: 'Microsoft YaHei', sans-serif;
}

/* 数据概览区域 */
.data-overview {
  margin-bottom: 20px;
}

.overview-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
}

.date {
  font-size: 14px;
  color: #666;
  font-weight: normal;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  transition: transform 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-card.sales {
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  color: white;
}

.stat-card.orders {
  background: linear-gradient(135deg, #ffa726, #ffb74d);
  color: white;
}

.stat-card.customers {
  background: linear-gradient(135deg, #42a5f5, #64b5f6);
  color: white;
}

.stat-card.delivery {
  background: linear-gradient(135deg, #ab47bc, #ba68c8);
  color: white;
}

.stat-card.target {
  background: linear-gradient(135deg, #66bb6a, #81c784);
  color: white;
}

.stat-icon {
  font-size: 24px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 12px;
  opacity: 0.9;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
}

/* 面板标题样式 */
.panel-header {
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.function-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 20px;
}

.functions-panel .function-grid {
  padding: 15px 20px 20px 20px;
  grid-template-columns: repeat(4, 1fr);
}

.function-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.function-item:hover {
  transform: scale(1.05);
}

.function-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  margin-bottom: 8px;
}

.function-name {
  font-size: 12px;
  color: #666;
  text-align: center;
}

/* 主要内容区域 */
.main-content {
  display: grid;
  grid-template-columns: 1fr 0.8fr;
  gap: 20px;
  margin-bottom: 20px;
  align-items: start;
}

.right-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-panel,
.functions-panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

/* 左侧面板 - 销售分析 */
.left-panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.panel-header {
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.chart-section {
  padding: 20px;
}

.pie-chart {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.pie-chart-container {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: conic-gradient(
    #4facfe 0deg 190deg,
    #ffa726 190deg 284deg,
    #66bb6a 284deg 324deg,
    #f56c6c 324deg 360deg
  );
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.pie-center {
  width: 120px;
  height: 120px;
  background: white;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.pie-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.pie-label {
  font-size: 12px;
  color: #666;
}

.customer-analysis {
  space-y: 10px;
}

.analysis-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.analysis-item:last-child {
  border-bottom: none;
}

.customer-type {
  font-size: 14px;
  color: #333;
}

.customer-amount {
  font-size: 14px;
  color: #666;
}

.customer-percent {
  font-size: 14px;
  font-weight: 600;
  color: #4facfe;
}

/* 进度条样式 */

.progress-section {
  padding: 20px;
}

.progress-item {
  margin-bottom: 25px;
}

.progress-item:last-child {
  margin-bottom: 0;
}

.progress-label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #4facfe, #00f2fe);
  border-radius: 10px;
  transition: width 0.3s ease;
}

.progress-value {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  text-align: right;
}

/* 底部订单列表 */
.orders-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
  margin-bottom: 10px;
}

.orders-section .section-header {
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.orders-section .section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.search-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input,
.filter-select,
.date-input {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-btn,
.reset-btn {
  padding: 6px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.search-btn {
  background: #409eff;
  color: white;
}

.reset-btn {
  background: #f0f0f0;
  color: #666;
}

.orders-table {
  overflow-x: auto;
}

.orders-table table {
  width: 100%;
  border-collapse: collapse;
}

.orders-table th,
.orders-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.orders-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.orders-table tr:hover {
  background: #f8f9fa;
}

.order-link {
  color: #409eff;
  text-decoration: none;
}

.order-link:hover {
  text-decoration: underline;
}

/* 分页样式 */
.table-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  background: #fafafa;
}

.pagination-info {
  font-size: 14px;
  color: #666;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.page-btn:hover:not(.disabled) {
  background: #ecf5ff;
  border-color: #b3d8ff;
  color: #409eff;
}

.page-btn.active {
  background: #409eff;
  border-color: #409eff;
  color: white;
}

.page-btn.disabled {
  background: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

.page-size-select {
  padding: 6px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  background: white;
  cursor: pointer;
  margin-left: 10px;
}

.page-size-select:focus {
  outline: none;
  border-color: #409eff;
}

.pagination {
  padding: 15px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  border-top: 1px solid #eee;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.pagination button.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination span {
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .main-content {
    grid-template-columns: 1fr 1fr;
  }
  
  .right-panel {
    grid-column: span 2;
  }
}

@media (max-width: 1024px) {
  .stats-cards {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .function-grid {
    grid-template-columns: repeat(4, 1fr);
  }
  
  .main-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .sales-workbench {
    padding: 10px;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .function-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .search-controls {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
